package com.example.demo.domain;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class BaseService<T> {
    protected BaseService(Class<T> clazz) { this.clazz = clazz; }

    private Class<T> clazz;

    @Autowired
    protected MongoTemplate mongoTemplate;

    protected Page<T> getPage(Pageable pageable, Criteria criteria){
        Query query = Query.query(criteria);
        long total = mongoTemplate.count(query,clazz);
        List<T> list = mongoTemplate.find(query.with(pageable), clazz);
        Page<T> page = new PageImpl<T>(list,pageable,total);
        return page;
    }
    protected List<T> getList(Criteria criteria){
        Query query = Query.query(criteria);
        return mongoTemplate.find(query,clazz);
    }
    protected String getCurrentDate(){
        Date date= new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        return dateFormat.format(date);
    }
    protected String getCurrentTime(){
        Date date= new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HHmmss");
        return dateFormat.format(date).split(" ")[1];
    }
}
